<?php

namespace app\common\libs;

use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Exception;

/*
 * 导入excel
 */

class ExcelLead
{

    protected static $_instance = null;

    //文件
    protected $file_name = null;
    protected $tmp_name = null;


    public static function getInstance($file_name, $tmp_name)
    {
        if (self::$_instance === null) {
            self::$_instance = new static();
        }

        self::$_instance->file_name = $file_name;
        self::$_instance->tmp_name = $tmp_name;

        return self::$_instance;
    }


    /**
     * 导入并返回数据
     * @throws Exception
     */
    public function excel_import()
    {

        ini_set('memory_limit', '1024M');
        $extension = $this->check_file(self::$_instance->file_name);

        if ($extension === "xlsx") {
            $objReader = IOFactory::createReader('Xlsx');
        } else {
            $objReader = IOFactory::createReader('Xls');
        }

        $objContent = $objReader->load(self::$_instance->tmp_name);
        if (!$objContent) {
            throw new Exception('导入失败', API_ERROR);
        }
        $sheetContent = $objContent->getSheet(0)->toArray();

        unset($sheetContent[0]);

        if (empty($sheetContent)){
            throw  new Exception('导入失败', API_ERROR);
        }

        return $sheetContent;
    }


    /**
     * 验证文件并返回路径
     * @throws Exception
     */
    private function check_file($file_name): string
    {

        if (empty($file_name)) {
            throw  new Exception('请先上传文件', API_ERROR);
        }
        $extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

        if ($extension !== 'xlsx' && $extension !== 'xls') {
            throw  new Exception('请先上传文件格式错误', API_ERROR);
        }

        return $extension;
    }


}
